package malus.shaofeng.com.beiwomusic.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import malus.shaofeng.com.beiwomusic.R;
import malus.shaofeng.com.beiwomusic.adapter.ClubTopicAdapter;
import malus.shaofeng.com.beiwomusic.model.HotPost;
import malus.shaofeng.com.beiwomusic.utils.Constants;
import malus.shaofeng.com.beiwomusic.view.SildingFinishLayout;
import malus.shaofeng.com.beiwomusic.view.Topbar;

@ContentView(R.layout.activity_bbs_club)
public class BbsClubActivity extends Activity implements Topbar.onTopbarClickListener,PullToRefreshBase.OnRefreshListener2<ListView> {
    int clubPosition;
    @ViewInject(R.id.sildingFinishLayout)
    SildingFinishLayout sildingFinishLayout;
    @ViewInject(R.id.topbar)
    Topbar topbar;
    @ViewInject(R.id.bbs_club_topic_list)
    PullToRefreshListView pullToRefreshListView;
    private ListView listView;
    private ArrayList<HotPost> data;
    private ClubTopicAdapter adapter;
    private int currentPage=1;
    private int totalPage=1;
    //刷新的handler
    private Handler onRefreshCompleteHandler =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.obj instanceof PullToRefreshBase){
                PullToRefreshBase refresh = (PullToRefreshBase) msg.obj;
                if(refresh!=null){
                    refresh.onRefreshComplete();
                }
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);

        pullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        pullToRefreshListView.setOnRefreshListener(this);
        listView = pullToRefreshListView.getRefreshableView();
        data =
                new ArrayList<>();
        adapter = new ClubTopicAdapter(this, data);
        listView.setAdapter(adapter);
        //滑动销毁
        sildingFinishLayout.setOnSildingFinishListener(new SildingFinishLayout.OnSildingFinishListener() {
            @Override
            public void onSildingFinish() {
                finish();
                overridePendingTransition(0, R.anim.trans_slider_out);
            }
        });
        //标题栏
        topbar.setOnTopbarClickListener(this);

        Intent intent = getIntent();
        if (intent != null) {
            clubPosition=intent.getIntExtra(Constants.BundleKey.KEY_BBS_CLUB,0);
        }
        //设置数据
        initData(null);
        //设置item的点击事件
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent1 = new Intent(BbsClubActivity.this,BBSTopicActivity.class);
                intent1.putExtra(Constants.BundleKey.KEY_BBS_TOPIC,data.get(position));
                startActivity(intent1);
            }
        });
    }

    private void initData(PullToRefreshBase<ListView> refreshView) {
        switch (clubPosition){
            case Constants.BundleKey.BBS_CLUB_CONDITION:
                topbar.setTitle("聊聊情事");
                setCondition(refreshView);
                break;
            case Constants.BundleKey.BBS_CLUB_PICTURE:
                topbar.setTitle("晒图美拍");
                setPicture(refreshView);
                break;
            case Constants.BundleKey.BBS_CLUB_NOTIFY:
                topbar.setTitle("站方公告");
                setNotify(refreshView);
                break;
            case Constants.BundleKey.BBS_CLUB_CHAT:
                topbar.setTitle("吐槽杂谈");
                setChat(refreshView);
                break;
        }
    }

    /**
     * 聊聊情事界面
     */
    private void setCondition(final PullToRefreshBase<ListView> refreshView) {
        HttpUtils httpUtils=new HttpUtils();
        String url = "http://kxai.cn/qms/ws/bbs/postList.json";
        RequestParams params = new RequestParams();
        params.addBodyParameter("page",currentPage+"");
        params.addBodyParameter("pageSize","10");
        httpUtils.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<Object>() {
            @Override
            public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                data.clear();
                String result = objectResponseInfo.result.toString();
                try {
                    JSONObject object=new JSONObject(result);
                    JSONObject response =object.getJSONObject("response");
                    JSONObject paginator = response.getJSONObject("paginator");
                    totalPage = paginator.getInt("total_page");

                    //获取推荐列表
                    if(!response.isNull("top_posts")){
                        JSONArray topPosts = response.optJSONArray("top_posts");
                        for (int i = 0; i < topPosts.length(); i++) {
                            JSONObject o = topPosts.getJSONObject(i);
                            HotPost hotPost=new HotPost();
                            hotPost.parseJSON(o);
                            hotPost.setTop(true);
                            data.add(hotPost);
                        }
                    }
                    //获取普通列表
                    JSONArray posts = response.getJSONArray("posts");
                    for (int i = 0; i < posts.length(); i++) {
                        JSONObject o = posts.getJSONObject(i);
                        HotPost hotPost=new HotPost();
                        hotPost.parseJSON(o);
                        data.add(hotPost);
                    }
                    adapter.notifyDataSetChanged();

                    //停止刷新
                    Message msg = new Message();
                    msg.obj=refreshView;
                    onRefreshCompleteHandler.sendMessageDelayed(msg, 200);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });
    }

    /**
     * 晒图美拍
     */
    private void setPicture(final PullToRefreshBase<ListView> refreshView) {
        HttpUtils httpUtils=new HttpUtils();
        String url = "http://kxai.cn/qms/ws/bbs/postList.json";
        RequestParams params = new RequestParams();
        params.addBodyParameter("page",currentPage+"");
        params.addBodyParameter("pageSize","10");
        params.addBodyParameter("forumId","4");
        httpUtils.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<Object>() {
            @Override
            public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                data.clear();
                String result = objectResponseInfo.result.toString();
                try {
                    JSONObject object=new JSONObject(result);
                    JSONObject response =object.getJSONObject("response");
                    JSONObject paginator = response.getJSONObject("paginator");
                    totalPage = paginator.getInt("total_page");
                    //获取推荐列表
                    if(!response.isNull("top_posts")){
                        JSONArray topPosts = response.optJSONArray("top_posts");
                        for (int i = 0; i < topPosts.length(); i++) {
                            JSONObject o = topPosts.getJSONObject(i);
                            HotPost hotPost=new HotPost();
                            hotPost.parseJSON(o);
                            hotPost.setTop(true);
                            data.add(hotPost);
                        }
                    }
                    //获取普通列表
                    JSONArray posts = response.getJSONArray("posts");
                    for (int i = 0; i < posts.length(); i++) {
                        JSONObject o = posts.getJSONObject(i);
                        HotPost hotPost=new HotPost();
                        hotPost.parseJSON(o);
                        data.add(hotPost);
                    }
                    adapter.notifyDataSetChanged();

                    //停止刷新
                    Message msg = new Message();
                    msg.obj=refreshView;
                    onRefreshCompleteHandler.sendMessageDelayed(msg, 200);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });
    }

    /**
     * 站方公告
     */
    private void setNotify(final PullToRefreshBase<ListView> refreshView) {
        HttpUtils httpUtils=new HttpUtils();
        String url = "http://kxai.cn/qms/ws/bbs/postList.json";
        RequestParams params = new RequestParams();
        params.addBodyParameter("page",currentPage+"");
        params.addBodyParameter("pageSize","10");
        params.addBodyParameter("forumId","5");
        httpUtils.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<Object>() {
            @Override
            public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                data.clear();
                String result = objectResponseInfo.result.toString();
                try {
                    JSONObject object=new JSONObject(result);
                    JSONObject response =object.getJSONObject("response");
                    JSONObject paginator = response.getJSONObject("paginator");
                    totalPage = paginator.getInt("total_page");
                    //获取推荐列表
                    if(!response.isNull("top_posts")){
                        JSONArray topPosts = response.optJSONArray("top_posts");
                        for (int i = 0; i < topPosts.length(); i++) {
                            JSONObject o = topPosts.getJSONObject(i);
                            HotPost hotPost=new HotPost();
                            hotPost.parseJSON(o);
                            hotPost.setTop(true);
                            data.add(hotPost);
                        }
                    }
                    //获取普通列表
                    JSONArray posts = response.getJSONArray("posts");
                    for (int i = 0; i < posts.length(); i++) {
                        JSONObject o = posts.getJSONObject(i);
                        HotPost hotPost=new HotPost();
                        hotPost.parseJSON(o);
                        data.add(hotPost);
                    }
                    adapter.notifyDataSetChanged();

                    //停止刷新
                    Message msg = new Message();
                    msg.obj=refreshView;
                    onRefreshCompleteHandler.sendMessageDelayed(msg, 200);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });
    }

    /**
     * 吐槽杂谈
     */
    private void setChat(final PullToRefreshBase<ListView> refreshView) {
        HttpUtils httpUtils=new HttpUtils();
        String url = "http://kxai.cn/qms/ws/bbs/postList.json";
        RequestParams params = new RequestParams();
        params.addBodyParameter("page",currentPage+"");
        params.addBodyParameter("pageSize","10");
        params.addBodyParameter("forumId","6");
        httpUtils.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<Object>() {
            @Override
            public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                data.clear();
                String result = objectResponseInfo.result.toString();
                try {
                    JSONObject object=new JSONObject(result);
                    JSONObject response =object.getJSONObject("response");
                    JSONObject paginator = response.getJSONObject("paginator");
                    totalPage = paginator.getInt("total_page");
                    //获取推荐列表
                    if(!response.isNull("top_posts")){
                        JSONArray topPosts = response.optJSONArray("top_posts");
                        for (int i = 0; i < topPosts.length(); i++) {
                            JSONObject o = topPosts.getJSONObject(i);
                            HotPost hotPost=new HotPost();
                            hotPost.parseJSON(o);
                            hotPost.setTop(true);
                            data.add(hotPost);
                        }
                    }
                    //获取普通列表
                    JSONArray posts = response.getJSONArray("posts");
                    for (int i = 0; i < posts.length(); i++) {
                        JSONObject o = posts.getJSONObject(i);
                        HotPost hotPost=new HotPost();
                        hotPost.parseJSON(o);
                        data.add(hotPost);
                    }
                    adapter.notifyDataSetChanged();

                    //停止刷新
                    Message msg = new Message();
                    msg.obj=refreshView;
                    onRefreshCompleteHandler.sendMessageDelayed(msg, 200);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });
    }
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(0,R.anim.trans_slider_out);
    }

    /**
     * topbar的三个事件
     */
    @Override
    public void onLeftButtonClick() {
        finish();
        overridePendingTransition(0,R.anim.trans_slider_out);
    }

    @Override
    public void onRightButtonClick() {
        if(clubPosition==Constants.BundleKey.BBS_CLUB_NOTIFY    ){
            Toast.makeText(this,"亲，官方公告不能发帖哦",Toast.LENGTH_SHORT).show();
        }else{
            Intent intent = new Intent(this,BbsPutTopicActivity.class);
            startActivity(intent);
        }
    }

    @Override
    public void onSearchButtonClick() {

    }

    /**
     * 上拉刷新下拉加载控件
     * @param refreshView
     */
    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        if(currentPage<=1){
            Toast.makeText(this,"亲，已经是第一页啦",Toast.LENGTH_SHORT).show();
            Message msg = new Message();
            msg.obj=refreshView;
            onRefreshCompleteHandler.sendMessageDelayed(msg, 200);
        }else{
            currentPage--;
            initData(refreshView);
        }
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        if(currentPage>=totalPage){
            Toast.makeText(this,"亲，已经是最后一页啦",Toast.LENGTH_SHORT).show();
            Message msg = new Message();
            msg.obj=refreshView;
            onRefreshCompleteHandler.sendMessageDelayed(msg, 200);
        }else{
            currentPage++;
            initData(refreshView);
        }
    }
}
